/**
 * @author Nicolas Lusa (lusan@usi.ch)
 */
package ch.usi.inf.pf2.gui.tool;

import java.awt.event.MouseEvent;

import ch.usi.inf.pf2.circuit.Component;
import ch.usi.inf.pf2.gui.Model;

public final class SelectionTool extends Tool {

	private Component currentShape;
	private int firstX;
	private int firstY;
	
    public SelectionTool(final Model model) {
        super(model, "Select this tool and click on a component to select and drag it.", "../icons/select.png", "../icons/selectBg.png");
        currentShape = null;
        firstX = 0;
        firstY = 0;
    }
    
    public void mouseClicked(final MouseEvent ev) {
        final int x = ev.getX();
        final int y = ev.getY();
        final Component shape = getCircuit().findShapeAt(x, y);
        if (!ev.isShiftDown()) {
            getSelection().clear();
        }
        if (shape!=null) {
            getSelection().add(shape);
        }
    }

    //DRAGGING
    
    public void mousePressed(final MouseEvent ev) {
        System.out.println("mousePressed: "+ev);
        currentShape = getCircuit().findShapeAt(ev.getX(), ev.getY());
        if (currentShape!=null) {
        	firstX = ev.getX();
        	firstY = ev.getY();
        	if (!ev.isShiftDown()) {
                getSelection().clear();
            }
            if (currentShape!=null) {
                getSelection().add(currentShape);
            }
        } else {
        	currentShape = null;
        }
    }
    
    public void mouseDragged(final MouseEvent ev) {
        System.out.println("mouseDragged: "+ev);
        if (currentShape!=null) {
        	currentShape.move(ev.getX() - firstX, ev.getY() - firstY);
        	getCircuit().shapeChanged();
        	firstX = ev.getX();
            firstY = ev.getY();
        }
    }

    public void mouseReleased(final MouseEvent ev) {
        System.out.println("mouseReleased: "+ev);
        if (currentShape!=null) {
        	currentShape.move(ev.getX() - firstX, ev.getY() - firstY);
        	getCircuit().shapeChanged();
        }
    }

}

